
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using JYJ.AiYard.StationManagement.TbRoadPayParams;
using JYJ.AiYard.StationManagement.TbRoadPayParams.Dtos;
using JYJ.AiYard.StationManagement.TbRoadPayParams.DomainService;
using JYJ.AiYard.StationManagement.TbRoadPayParams.Authorization;
using JYJ.AiYard.Database;
using Microsoft.AspNetCore.Http;
using JYJ.AiYard.StationManagement.YardCommonHald;
using JYJ.AiYard.StationManagement.YardReport;
using AiYard.Common;

namespace JYJ.AiYard.StationManagement.TbRoadPayParams
{
    /// <summary>
    /// TbRoadPayParams应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbRoadPayParamsAppService : AiYardAppServiceBase, ITbRoadPayParamsAppService
    {
        private readonly IRepository<TbRoadPayParams, long> _entityRepository;

        private readonly ITbRoadPayParamsManager _entityManager;
		private readonly IHttpService _httpService;

		protected IHttpContextAccessor _httpContext;

		/// <summary>
		/// 构造函数 
		///</summary>
		public TbRoadPayParamsAppService(
        IRepository<TbRoadPayParams, long> entityRepository
        ,ITbRoadPayParamsManager entityManager
		,IHttpService httpService
		,IHttpContextAccessor httpContextAccessor
		)
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
			_httpService = httpService;
			_httpContext = httpContextAccessor;
		}


        /// <summary>
        /// 获取TbRoadPayParams的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbRoadPayParamsPermissions.Query)] 
        public async Task<PagedResultDto<TbRoadPayParamsListDto>> GetPaged(GetTbRoadPayParamssInput input)
		{
			List<long> StationList = new List<long>();
			tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
			if (filterText.StationId == null || filterText.StationId <= 0)
			{
				StationList = GetCurrenUserOrganizationAndChildrenUnit();
			}
			else
			{
				StationList.Add((long)filterText.StationId);
			}
			var query = _entityRepository.GetAll().Where(o => StationList.Contains(o.Station_ID));
			// TODO:根据传入的参数添加过滤条件
            

			var count = await query.CountAsync();

			var entityList = await query               
                    .OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			var entityListDtos =entityList.MapTo<List<TbRoadPayParamsListDto>>();

			return new PagedResultDto<TbRoadPayParamsListDto>(count,entityListDtos);
		}


		/// <summary>
		/// 通过指定id获取TbRoadPayParamsListDto信息
		/// </summary>
		[AbpAuthorize(TbRoadPayParamsPermissions.Query)] 
		public async Task<TbRoadPayParamsListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbRoadPayParamsListDto>();
		}

		/// <summary>
		/// 获取编辑 TbRoadPayParams
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbRoadPayParamsPermissions.Create,TbRoadPayParamsPermissions.Edit)]
		public async Task<GetTbRoadPayParamsForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbRoadPayParamsForEditOutput();
            TbRoadPayParamsEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbRoadPayParamsEditDto>();

			}
			else
			{
				editDto = new TbRoadPayParamsEditDto();
			}

			output.TbRoadPayParams = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbRoadPayParams的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbRoadPayParamsPermissions.Create,TbRoadPayParamsPermissions.Edit)]
		public async Task CreateOrUpdate(CreateOrUpdateTbRoadPayParamsInput input)
		{
            if (input.TbRoadPayParams.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            }
            if (input.TbRoadPayParams.Id.HasValue)
			{
				await Update(input.TbRoadPayParams);
			}
			else
			{
				await Create(input.TbRoadPayParams);
			}
		}


		/// <summary>
		/// 注册回调函数
		/// </summary>
		/// <param name="StationId"></param>
		/// <param name="CaleMoneyNotify"></param>
		/// <param name="PaySuccessNotify"></param>
		/// <param name="InvoiceNotify"></param>
		/// <param name="FindCarNotify"></param>
		/// <returns></returns>
		[AbpAuthorize(TbRoadPayParamsPermissions.Create, TbRoadPayParamsPermissions.Edit)]
		public async Task<string> roadpathurl(int StationId, string CaleMoneyNotify, string PaySuccessNotify, string InvoiceNotify, string FindCarNotify)
		{
			try
			{
				string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
				host = "localhost"; 
#endif
				string Url1 = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardRoad/roadpathurl?StationId=" + StationId + "&url=" + CaleMoneyNotify + "&notify=停车缴费";
				string Url2 = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardRoad/roadpathurl?StationId=" + StationId + "&url=" + PaySuccessNotify + "&notify=支付成功";
				string Url3 = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardRoad/roadpathurl?StationId=" + StationId + "&url=" + InvoiceNotify + "&notify=发票开具";
				string Url4 = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardRoad/roadpathurl?StationId=" + StationId + "&url=" + FindCarNotify + "&notify=场内寻车";
				AiLogger.Instance.WriteLog(Url1, "回调路政");
                AiLogger.Instance.WriteLog(Url2, "回调路政");
                AiLogger.Instance.WriteLog(Url3, "回调路政");
                AiLogger.Instance.WriteLog(Url4, "回调路政");
                string jLQr1 = _httpService.Get(Url1).Trim();
				string jLQr2 = _httpService.Get(Url2).Trim();
				string jLQr3 = _httpService.Get(Url3).Trim();
				string jLQr4 = _httpService.Get(Url4).Trim();

                AiLogger.Instance.WriteLog(jLQr1, "回调路政");
                AiLogger.Instance.WriteLog(jLQr2, "回调路政");
                AiLogger.Instance.WriteLog(jLQr3, "回调路政");
                AiLogger.Instance.WriteLog(jLQr4, "回调路政");
                if (jLQr1 == "" || jLQr2 == "" || jLQr3 == "" || jLQr4 == "")
				{
					return "注册路政回调函数错误";
				}
				ApiResult jLQr11 = Json.ToObject<ApiResult>(jLQr1);
				ApiResult jLQr12 = Json.ToObject<ApiResult>(jLQr2);
				ApiResult jLQr13 = Json.ToObject<ApiResult>(jLQr3);
				ApiResult jLQr14 = Json.ToObject<ApiResult>(jLQr4);

				if (jLQr11.result != 1 || jLQr12.result != 1 || jLQr13.result != 1 || jLQr14.result != 1)
				{
					return "注册【停车缴费--" + jLQr11.msg + "】【支付成功--" + jLQr12.msg + "】【发票开具--" + jLQr13.msg + "】【场内寻车--" + jLQr14.msg + "】";
				}
				else
				{
					return "注册路政回调函数成功";
				}

			}
			catch (Exception ex)
			{
				return "注册路政回调函数异常";
			}
		}

		/// <summary>
		/// 新增TbRoadPayParams
		/// </summary>
		[AbpAuthorize(TbRoadPayParamsPermissions.Create)]
		protected virtual async Task<TbRoadPayParamsEditDto> Create(TbRoadPayParamsEditDto input)
		{
            if (string.IsNullOrEmpty(input.Client_ID.ToString()))
                input.Client_ID = 0;

            

            //判断相同的客户端是否只存在一个
            var query = _entityRepository.GetAll()
                .Where(o => o.Client_ID == input.Client_ID && o.Station_ID == input.Station_ID);
            if (query.Count() > 0)
            {
                throw new UserFriendlyException("存在相同活动的客户端支付参数设置");
            }

            // var entity = ObjectMapper.Map <TbRoadPayParams>(input);
            var entity=input.MapTo<TbRoadPayParams>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<TbRoadPayParamsEditDto>();
		}

		/// <summary>
		/// 编辑TbRoadPayParams
		/// </summary>
		[AbpAuthorize(TbRoadPayParamsPermissions.Edit)]
		protected virtual async Task Update(TbRoadPayParamsEditDto input)
		{
            if (string.IsNullOrEmpty(input.Client_ID.ToString()))
                input.Client_ID = 0;


            //判断相同的客户端是否只存在一个
            var query = _entityRepository.GetAll()
                .Where(o => o.Client_ID == input.Client_ID && o.Station_ID == input.Station_ID && o.Id != input.Id);
            if (query.Count() > 0)
            {
                throw new UserFriendlyException("存在相同活动的客户端支付参数设置");
            }

            var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除TbRoadPayParams信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbRoadPayParamsPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbRoadPayParams的方法
		/// </summary>
		[AbpAuthorize(TbRoadPayParamsPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		///// <summary>
		///// 导出TbRoadPayParams为excel表,等待开发。
		///// </summary>
		///// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


